package com.example.blog.controller;

import com.example.blog.common.R;
import com.example.blog.dao.UserDAO;
import com.example.blog.model.User;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@CrossOrigin
@RestController
public class UserController {
    @Resource
    public UserDAO userDAO;

    @PostMapping("/register")
    public Object register(@RequestParam String username, @RequestParam String password) {
        User user = userDAO.findByUsername(username);
        if (user != null) {
            return R.fail();
        }

        user = new User(username, password);
        userDAO.save(user);
        return R.success();
    }

    @PostMapping("/login")
    public Object login(@RequestParam String username, @RequestParam String password) {
        User user = userDAO.findByUsernameAndPassword(username, password);
        if (user != null) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("userId", user.id);
            return R.success(map);
        } else {
            return R.fail();
        }
    }

    @GetMapping("/user/list")
    public Object login() {
        List<User> users = userDAO.findAll();
        return R.success(users);
    }

    @GetMapping("/user/profile")
    public Object getUserProfile(@RequestParam int id) {
        User user = userDAO.findById(id).get();
        return R.success(user);
    }

    @PostMapping("/user/profile")
    public Object updateUserProfile(@RequestBody User user) {
        User userInDB = userDAO.findById(user.id).get();
        userInDB.password = user.password;
        userDAO.save(userInDB);
        return R.success();
    }
}
